<?php
/*
 * @Author: 李红雨 - RainLee <rainlee1990@yeah.net>
 * @Date: 2022-03-10 14:17:01
 * @LastEditors: 李红雨 - RainLee <rainlee1990@yeah.net>
 * @LastEditTime: 2022-03-15 10:35:17
 * @Description: File Description
 */

namespace rainlee\auth\provider;

use InvalidArgumentException;
use think\facade\Config;

trait CreateUserProviders
{

    /**
     * 创建用户驱动
     * 
     * @param string $name
     * @return \rainlee\auth\provider\DatabaseUserProvider|\rainlee\auth\provider\ModelUserProvider
     * 
     * @throws \think\Exception
     */
    public function createUserProviders($name = null)
    {
        $provider = $this->getProviderConfig($name);

        $driver = $provider['driver'] ?? null;

        switch ($driver) {
            case 'database':
                return $this->createDatabaseProvider($provider);
            case 'model':
                return $this->createModelProvider($provider);
            default:
                throw new InvalidArgumentException("Authentication user provider [{$driver}] is not defined.");
        }
    }

    protected function getProviderConfig($name)
    {
        return Config::get("auth.providers.{$name}");
    }

    /**
     * 创建用户数据库实例
     * 
     * @param array $config
     * @return \rainlee\auth\provider\DatabaseUserProvider
     */
    protected function createDatabaseProvider($config)
    {
        return new DatabaseUserProvider($config);
    }

    /**
     * 创建用户模型实例
     * 
     * @param array $config
     * @return \rainlee\auth\provider\ModelUserProvider
     */
    protected function createModelProvider($config)
    {
        return new ModelUserProvider($config);
    }
}
